package com.hxzy.controller.hsbuilding;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.util.BeanValidatorUtil;
import com.hxzy.common.BaseServlet;
import com.hxzy.common.ResultAjax;
import com.hxzy.entity.Build;
import com.hxzy.service.BuildService;
import com.hxzy.service.impl.BuildServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;

/**
 * @Description:
 * @Author: ykj
 * @Date: 2022/3/8 18:47
 */
@WebServlet(urlPatterns = "/add/build")
public class AddJsonServlet extends BaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        try {
            Build build = super.CollectiongParameterToJSON(req, Build.class);
            build.setId(UUID.randomUUID().toString().replace("-",""));
            Set<String> validator = BeanValidatorUtil.validator(Build.class, build);
            if (validator.isEmpty()){
                BuildService service=new BuildServiceImpl();
                int insert = service.insert(build);
                ResultAjax resultAjax;
                if (insert>0){
                    resultAjax=ResultAjax.succss_data(build);
                }else {
                    resultAjax=ResultAjax.error("加入失败");
                }
                super.render(resp, JSONObject.toJSONString(resultAjax));
            }else {
                String next = validator.iterator().next();
                ResultAjax error = ResultAjax.error(next);
                super.render(resp, JSONObject.toJSONString(error));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
